import urllib

from flask_socketio import SocketIO, send, emit, leave_room, join_room

from app import *
from pymongo import MongoClient
conn = MongoClient()
db = conn.md
table = db.socket_message
from tools import MyRedis,MyMongo
socketio = SocketIO(app,cors_allowed_origins='*')
import arrow
import json 

@socketio.on('message_push')
def handle_message(data):
    data = eval(urllib.parse.unquote(data))
    sid=request.sid
    # 查询是否存在
    print(data,sid)
    with MyMongo(db='md',table='message_box') as c: 
        res = c.find_one({'title':data['title']})
        if res:
            pass
        else:
            # 如果有延时发送
            if int(data['is_set_timing']):
                print(data)
                # 添加进延时队列中
                with MyRedis()as r:
                    r.hset('timing_send', str(data), data['timing'])
                c.insert_one({
                    'title':data['title'],
                    'priority':data['priority'],
                    'machine_type':data['check_list'],
                    'sendtime':'',
                    'timing': data['timing'],
                    'is_set_timing':data['is_set_timing'],
                    'place':data['place'],
                })
            else:
                # 生成时间对象
                n =arrow.now()
                c.insert_one({
                    'title':data['title'],
                    'priority':data['priority'],
                    'machine_type':data['check_list'],
                    'sendtime':n.format('YYYY-MM-DD HH:mm:ss'),
                    'timing': data['timing'],
                    'is_set_timing': data['is_set_timing'],
                    'place': data['place'],
                })
                send(json.dumps(data,ensure_ascii=False),broadcast=True)

@socketio.on('message')
def handle_message(message):
    message = urllib.parse.unquote(message)
    sid=request.sid
    # 查询该链接是否有
    msg_list= list(table.find({'sid':sid}))
    if msg_list:
        msgs=msg_list[0]['msg']
        msgs.append(message)
        table.update_one({'sid': sid},{'$set': {'msg':msgs}})
    else:
        # 做为记录存储
        with MyRedis()as c:
            c.lpush('channels',sid)
        table.insert_one({'sid':sid,'msg':[message],'is_reply':0,'replyer':''})
    send(message)


# 加入房间
@socketio.on('join')
def on_join(data):
    data = eval(urllib.parse.unquote(data))
    username = data['username']
    room = data['room']
    join_room(room)
    send('客服'+username + '进入房间', room=room)

# 定时发送
@socketio.on('timing_send')
def timing_send(data):
    print(data)
    # with MyMongo(db='md',table='message_box') as c:
    #     n = arrow.now()
    #     c.update_one({'title':eval(data)['title']}, {'$set': {'sendtime':n.format('YYYY-MM-DD HH:mm:ss')}})
    send(json.dumps(data, ensure_ascii=False), broadcast=True)

@socketio.on('onroom')
def on_room(message,room):
    message = urllib.parse.unquote(message)
    # 查询该链接是否有
    msg_list= list(table.find({'sid':room}))
    if msg_list:
        msgs=msg_list[0]['msg']
        msgs.append(message)
        table.update_one({'sid': room},{'$set': {'msg':msgs}})
    send(message,room=room)

@socketio.on('leave')
def on_leave(data):
    data = eval(urllib.parse.unquote(data))
    username = data['username']
    room = data['room']
    leave_room(room)
    send(username + ' 离开了房间', room=room)

@socketio.on('connect', namespace='/chat')
def test_connect():
    emit('my response', {'data': 'Connected'})

@socketio.on('disconnect', namespace='/chat')
def test_disconnect():
    print('Client disconnected')

@app.route("/timing_send/",methods=['GET'])
def timing_send():
    data= request.args.get('data')
    print(type(data),data)
    dataj = json.dumps(eval(data))
    socketio.emit('timing_send',dataj)
    return 'ok'

if __name__ == '__main__':
    # app.run(debug=True,host="0.0.0.0",port=5000)
    socketio.run(app, debug=True, host="0.0.0.0", port=5002)
